package top.tagao.m03_beHavioralPatterns.b_12_Iterator.iterators;

import top.tagao.m03_beHavioralPatterns.b_12_Iterator.profile.Profile;
import top.tagao.m03_beHavioralPatterns.b_12_Iterator.social_networks.Facebook;
import top.tagao.m03_beHavioralPatterns.b_12_Iterator.social_networks.LinkedIn;
import top.tagao.m03_beHavioralPatterns.b_12_Iterator.social_networks.SocialNetwork;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Viktor_Liu
 * @Date 2022/8/14 23:35
 */
public class LinkedInIterator implements ProfileIterator {
    private LinkedIn linkedIn;
    private String type;
    private String email;
    private int currentPosition = 0;
    private List<String> emails = new ArrayList<>();
    private List<Profile> profiles = new ArrayList<>();
    
    public LinkedInIterator(LinkedIn linkedIn,String type, String email) {

        //linkedIn 包含所有 Profile的所以信息
        this.linkedIn = linkedIn;
        this.type = type;
        this.email = email;

        //懒加载 提前赋值
        lazyLoad();
    }

    private void lazyLoad() {
        if (emails.size() == 0){
            List<String> profiles =
                    linkedIn.requestProfileFriendsFromLinkedIn(this.email, this.type);
            for (String profileEmail: profiles) {
                this.emails.add(profileEmail);
                this.profiles.add(null);
            }

        }
    }

    @Override
    public boolean hasNext() {
        return currentPosition < emails.size();
    }

    @Override
    public Profile getNext() {
        if (!hasNext()) {
            return null;
        }
        String friendEmail = emails.get(currentPosition);

        Profile friendProfile = profiles.get(currentPosition);
        if (friendProfile == null){
            friendProfile = linkedIn.requestProfileFromLinkedIn(friendEmail);
            profiles.set(currentPosition,friendProfile);
        }
        currentPosition++;
        return friendProfile;
    }

    @Override
    public void reset() {
        currentPosition = 0;
    }
}
